package servlet;

import DBUtils.strUtils.StrUtils;
import Dao.UserDao;
import Dao.UserDaoImpl;
import bean.User;
import myspringmvc.ViewBaseServlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;

@WebServlet("/user.do")
public class UserServlet extends ViewBaseServlet {
    private UserDao userDao = new UserDaoImpl();
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");

        String operate = request.getParameter("operate");
        if (StrUtils.isEmpty(operate)){
            operate = "index";
        }
        switch (operate){
            case "index":
                index(request,response);
                break;
            case "add":
                add(request,response);
                break;
            case "del":
                del(request, response);
                break;
            case "edit":
                edit(request, response);
                break;
            case "update":
                update(request, response);
                break;
            default:
                throw new RuntimeException("运行时异常");
        }
    }

    private void update(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        request.setCharacterEncoding("utf-8");

        //获取参数
        String userID = request.getParameter("userID");
        int id = Integer.parseInt(userID);
        String name = request.getParameter("userName");
        String userBalance = request.getParameter("balance");
        double balance = Double.parseDouble(userBalance);

        userDao.update(new User(id,name,balance));
        //userDao.update(new User(id,name,balance));这步执行结束时，数据已经更新，但是index页面的数据却没有变化

//        super.processTemplate("index",request,response);
//        super.processTemplate("index",request,response);这句话的作用就如同请求转发，会直接跳转到index页面
//        页面不更新的原因是，session中保存的还是第一次请求时，查询到的数据，
//        所以此处应该重定向，让session重新请求一次，刷新保存作用域显示在页面上
//        所以采用重定向
        response.sendRedirect("user.do");


    }

    private void edit(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //从index页面中获取点击超链接获取的userID
        String userID = request.getParameter("userID");
        if (StrUtils.isNotEmpty(userID)){
            int id = Integer.parseInt(userID);
            //通过这个ID，在数据库中查询这条记录
            User user = userDao.selectOneInfo(id);
            //将user保存到request.setAttruibute保存作用域
            request.setAttribute("user",user);
            //然后跳转到另外一个页面
            super.processTemplate("edit",request,response);
//            request.getRequestDispatcher("edit.html").forward(request,response);

        }
    }

    private void del(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //从请求中获取传过来的参数
        String userID = request.getParameter("userID");
        //如果参数不为空，调用baseDao中的delete方法，删除元素
        if (StrUtils.isNotEmpty(userID)){
            int id = Integer.parseInt(userID);
            userDao.delete(id);
        }
        //将数据删除以后，重定向到index页面
        response.sendRedirect("user.do");
    }

    private void add(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");

        String userId = request.getParameter("userID");
        int id = Integer.parseInt(userId);

        String name = request.getParameter("userName");

        String userBalance = request.getParameter("balance");
        double balance = Double.parseDouble(userBalance);

        //调用Dao中的方法，将浏览器传入的数据，保存到到数据库
        User user = new User(id,name,balance);

        //测试插入,没问题
        userDao.insertInfo(user);
        //插入成功跳转到index
        response.sendRedirect("user.do");

    }

    private void index(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        //当前是第userNum个员工
        int userNum = 1;
        //当前页数为pageCount
        int pageCount = 1;

        //1.设置编码
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        //2.获取session
        HttpSession session = request.getSession();
        //从科幻段获取当前是否为查询需求
        String oper = request.getParameter("oper");
        String keyWord = null;
        //是查询需求
        if (StrUtils.isNotEmpty(oper) && "search".equals(oper)){
            //如果oper不为空，则采用dopost方式传递
            pageCount = 1;
            keyWord = request.getParameter("keyWordsName");
            if (StrUtils.isEmpty(keyWord)){
                keyWord = "";
            }
            session.setAttribute("keyWord",keyWord);
            //不是查询需求，是翻页需求
        }else {
            //否则为doget
            /*
            只有触发了鼠标点击事件，才会激活以下语句，将客户端请求响应给服务器
            鼠标点击下一页，获取当前页面是第几个页面,pageNum为从浏览器传入的页码
            服务器判断传入的参数是否为空，不为空就会将参数转换成数字，跳转页面
             */
            String pageCountStr = request.getParameter("pageNum");
            if (StrUtils.isNotEmpty(pageCountStr)){
                pageCount = Integer.parseInt(pageCountStr);
                userNum = pageCount;
            }
            Object keyWordObj = session.getAttribute("keyWord");
            if (keyWordObj != null){
                keyWord = (String) keyWordObj;
            }else {
                keyWord = "";
            }
        }

        //3.调用查询从0开始的页面每页存五条数据
        List<User> userList = userDao.selectManInfo(keyWord,(userNum-1)*5);
        userNum = 1;
        //将页面数量保存到session中
        session.setAttribute("pageCount",pageCount);

        //获取总页数
        Long nums = userDao.selectNums(keyWord);
        String value = String.valueOf(nums);
        int userCount = Integer.parseInt(value);
        int pageCountSub = (userCount + 4) / 5;
        //将页面总数保存到页面中
        session.setAttribute("pageCountSub",pageCountSub);

        //4.将获取道德数据保存到session作用域中
        session.setAttribute("userList",userList);

        //5.跳转到页面
        /*
            此处的视图名称为index
            thymeleaf会将 逻辑视图名称 对应到 物理视图名称上去
            逻辑视图名称：index
            物理视图名称：view-prefix + 逻辑视图名称 + view-suffix
            所以真实的视图名称： /          index       .html
         */
        super.processTemplate("index",request,response);
    }

}
